//
//  WBGetStatusesViewModel.m
//  sinaWeibo
//
//  Created by 李江波 on 2016/11/17.
//  Copyright © 2016年 lijiangbo. All rights reserved.
//

#import "WBGetStatusesViewModel.h"
#import "WBOAuthViewModel.h"
#import "LEEHTTPManager.h"
#import <YYModel.h>

#import "WBStatusesModel.h"
#import "WBStatuseInfoViewModel.h"
#import <SDWebImageManager.h>

#import "WBStatuseDAL.h"
#import "WBHomeCell.h"

@interface WBGetStatusesViewModel ()


@property(nonatomic ,strong) WBHomeCell *wbHomeCell;
@property(nonatomic ,strong) WBHomeCell *wbRetweetedCell;



@end

@implementation WBGetStatusesViewModel
static WBGetStatusesViewModel *_instance;
+(instancetype)shared{

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc]init];
        
    });
    return _instance;
}

-(WBHomeCell *)wbHomeCell{

    if (nil == _wbHomeCell) {
       
        UINib *nib = [UINib nibWithNibName:@"WBHomeCell" bundle:nil];
        _wbHomeCell = [[nib instantiateWithOwner:nil options:nil] lastObject];
        
    }
    return _wbHomeCell;
}
-(WBHomeCell *)wbRetweetedCell{
    
    if (nil == _wbRetweetedCell) {
        
        UINib *nib = [UINib nibWithNibName:@"WBRetwwetCell" bundle:nil];
        _wbRetweetedCell = [[nib instantiateWithOwner:nil options:nil] lastObject];
        
    }
    return _wbRetweetedCell;
}

#pragma mark : - 加载微博数据
-(void)loadData:(BOOL)isPullup completion:(void (^)(BOOL , NSInteger))completion{
    
//    NSString *urlStr = @"https://api.weibo.com/2/statuses/home_timeline.json";
    
    NSString *max_id = @"0";
    //若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博）
    NSString *since_id = @"0";
//    NSDictionary *dict;
//    NSString *access_token = [WBOAuthViewModel shared].userModel.access_token;
    
    if (isPullup) {
        NSInteger id_num = self.arrayStatuses.lastObject.statuse.iid;
        id_num -= 1;
        max_id = @(id_num).description;
        
    }else{
        if (self.arrayStatuses.count != 0) {
            
            NSInteger sinceid = self.arrayStatuses.firstObject.statuse.iid;
            since_id = @(sinceid).description;
        }else{
        
            since_id = @"1";
        }
    }

#warning :后来一种方法更简单。直接判断加载数据个数。如果等于20.直接删掉后面数组。如果小于20就加在数组前面！！！！！
    
        [[WBStatuseDAL new] loadHomeData:since_id max_id:max_id finished:^(NSArray<NSDictionary *> *array) {
            
            if (array.count == 0) {
                
                completion(true, 0);
                return ;
            }
    
        NSMutableArray<WBStatuseInfoViewModel *> *arrayM = [NSMutableArray array];
        
        for (NSDictionary *item in array) {
            
            WBStatuseInfoViewModel *statuseModel = [[WBStatuseInfoViewModel alloc]init];
            
            WBStatusesModel *model = [[WBStatusesModel alloc]init];
            [model yy_modelSetWithDictionary:item];
            
            statuseModel.statuse = model;
            
            if (statuseModel.imgURLs.count != 1) {
                
                WBHomeCell *cell = [self chooseCellWithModel:statuseModel];
                cell.model = statuseModel;
                [cell layoutIfNeeded];
                statuseModel.rowHeight = CGRectGetMaxY(cell.threeBtn.frame);
            }
            
            [arrayM addObject:statuseModel];
        }
        
//        self.newArrayCount = arrayM.count;
        if (isPullup) {
            
            self.arrayStatuses = [self.arrayStatuses arrayByAddingObjectsFromArray:arrayM].mutableCopy;
            
            [self cacheStatusSingleImage:arrayM completion:completion];
            
        }else{
        
            if (arrayM.count < 20) {
                
                self.arrayStatuses = [arrayM arrayByAddingObjectsFromArray:self.arrayStatuses].mutableCopy;
            } else {
                
                [self.arrayStatuses removeAllObjects];
                self.arrayStatuses = arrayM;
            }
    
            [self cacheStatusSingleImage:arrayM completion:completion];
        }
        
    }];
    
}

//单张图片下载
-(void)cacheStatusSingleImage:(NSMutableArray<WBStatuseInfoViewModel *>*)array completion:(void(^)(BOOL isSuccess, NSInteger count))completion{
    
    dispatch_group_t group = dispatch_group_create();
    
    for (WBStatuseInfoViewModel *item in array) {
        
        if (item.imgURLs.count == 1) {
            
            dispatch_group_enter(group);
            NSURL *url = [NSURL URLWithString:item.statuse.pic_urls.lastObject.wap360];
            [[SDWebImageManager sharedManager] downloadImageWithURL:url options:2 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                
                NSLog(@"单张图片下载完成");
                dispatch_group_leave(group);
            }];
        }
    }
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        
        for (WBStatuseInfoViewModel *statuseModel in array) {
            
            WBHomeCell *cell = [self chooseCellWithModel:statuseModel];
            cell.model = statuseModel;
            [cell layoutIfNeeded];
            statuseModel.rowHeight = CGRectGetMaxY(cell.threeBtn.frame);
        }
        
        
        
        completion(true,array.count);
        
    });
    
}

-(WBHomeCell *)chooseCellWithModel:(WBStatuseInfoViewModel *)model {

    if (model.statuse.retweeted_status == nil) {
        
        return self.wbHomeCell;
    } else {
        
        return self.wbRetweetedCell;
    }
    
}

@end
